package zcw.com.lib_leet_code;

/**
 * Created by 朱城委 on 2022/1/27.<br><br>
 *
 * 中等：寻找峰值
 */
public class Topic162 {

    public static void main(String[] args) {
        Topic162 instance = new Topic162();

        int[] array = new int[] {1,2,3,1};
        System.out.println(instance.findPeakElement(array));

        array = new int[] {1,2,1,3,5,6,4};
        System.out.println(instance.findPeakElement(array));
    }

    public int findPeakElement(int[] nums) {
        if(nums.length < 2) {
            return 0;
        }

        return helper(nums, 0, nums.length - 1);
    }

    private int helper(int[] nums, int start, int end) {
        if(start > end) {
            return -1;
        }

        int middle = (start + end);
        if(middle == 0) {
            if(nums[middle] > nums[middle + 1]) {
                return middle;
            }
        }
        else if(middle == nums.length - 1) {
            if(nums[middle] > nums[middle - 1]) {
                return middle;
            }
        }
        else if(nums[middle] > nums[middle - 1] && nums[middle] > nums[middle + 1]) {
            return middle;
        }

        int tempStart = helper(nums, start, middle - 1);
        int tempEnd = helper(nums, middle + 1, end);

        return tempStart == -1 ? tempEnd : tempStart;
    }
}
